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.

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

	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;



About The Author

Deependra Kushwah
Deependra kushwah is a member of the fastest growing bloggers community "betechnical", Author, Youtuber, and hardcore Coder. I love writing code in different languages, I also write blogs on tech tutorials, gadgets review and also post some technical videos on youtube on many topics.

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