How to Migrate Existing Web API Controllers by Using a Compatibility Shim

.NET and Microsoft decided to merge the MVC and Web API functionality, after the release of ASP.NET. If you are looking for the implementation of Web API with ASP.NET, Here is the way to accomplish:

Migrating Existing Web API Controllers by Compatibility Shim

You will have to alter one code to call AddWebApiConventions() if you use HttpResponseMessage in Web API controllers. It will help to know the proper serialize that response by wiring up the HttpResponseMessageOutputFormatter.

public void ConfigureServices(IServiceCollection services)
{
	// Add framework services.
	services.AddMvc().AddWebApiConventions(); //Add WebApi
}

}Depending upon your routing with Web API. You will need to register routes with Startup class.

In this way, you can migrate from your Web API code to ASP.NET Core. 

public void Configure(IApplicationBuilder app, 
                IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseMvc(routes =>
    {
	routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
    });
}

This sample controller helps you to use your ApiController within ASP.NET Core with compatibility Shim.

[Route("api/[controller]/[action]")]
public class ValuesApiController : ApiController
{
	[HttpGet]
	[ActionName("GetArray")]
	public IEnumerable GetArray()
	{
		//example returns a basic type that is automatically serialized as json - nothing special here
		return new string[] { "value2", "value3" };
	}

	[HttpGet]
	[ActionName("GetSomeJson")]
	public HttpResponseMessage GetSomeJson()
	{
		//example returns a HttpResponseMessage - the shim makes this possible
		var resp = new HttpResponseMessage()
		{
			Content = new StringContent("[{\"Name\":\"ABC\"},[{\"A\":\"1\"},{\"B\":\"2\"},{\"C\":\"3\"}]]")
		};

		resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
		return resp;
	}
}

 

Catch us on social media

Author Profile

Deependra Kushwah
Deependra Kushwah
Deependra is a Senior Developer with Microsoft technologies, currently working with Opteamix India business private solution. In My Free time, I write blogs and make technical youtube videos. Having the good understanding of Service-oriented architect, Designing microservices using domain driven design.

Deependra Kushwah

Deependra is a Senior Developer with Microsoft technologies, currently working with Opteamix India business private solution. In My Free time, I write blogs and make technical youtube videos. Having the good understanding of Service-oriented architect, Designing microservices using domain driven design.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

RSS
Facebook
Google+
https://betechnical.blog/2018/01/12/how-to-migrate-existing-web-api-controllers-by-using-a-compatibility-shim">
Twitter
YouTube
Pinterest
Pinterest
LinkedIn
Instagram
%d bloggers like this: