Renu R Renu R - 3 months ago 19
C# Question

MVC Controller to API Controller

I have an MVC Controller already written. Now, I have to code the same action methods of the MVC Controller to a new API Controller.

What all changes would be needed to put a method in the API Controller?

For Eg. MVC Controller Code

[HttpGet]
[EAuthorize(xyz)]
public ActionResult Trans()
{
var user = (User)WebSession.CurrentUser;
var mTrans = mTransLMgr.InitializeMTrans(user.currentSelectedEntity.Value);
mTransLMgr.AccNum = TController.GetAccountNumberBasedOnPrivilage(x,y);
return View(mTransLMgr);
}


If I have to implement the same method in an API Controller, what are the changes I will have to implement. The methods should return JSON.

Answer

You cannot convert a MVC controller to an API Controller. Both types devires from different base classes. In ASP.NET MVC a controller have to derive from Controller class, while in ASP.NET WEB API a controller the base class is a ApiController. In both cases, you inherit from a custom controller base, but this one must inherit from the original base controller provided by the plataform.

In ASP.NET WEB API, the result format is provided by content-type provided on the http header. So, your client application must provided the application/json on the content-type attribute and the ASP.NET WEB API will serialize in this format for you. For Sample:

public HttpResponseMessage Get(int id)
{
    var user = (User)WebSession.CurrentUser;

    var mTrans = mTransLMgr.InitializeMTrans(user.currentSelectedEntity.Value);        
    mTransLMgr.AccNum = TController.GetAccountNumberBasedOnPrivilage(x,y);            

    // return ok with the model serialized on the response body
    Request.CreateResponse(HttpStatus.Ok, mTransLMgr);    
} 

I am not sure what you have on the WebSession.CurrentUser, but if you use a key on the HttpContext.Session[key] you cannot do this because ASP.Net is stateless and you do not have sessions.

For the EAuthorize you have to implement authentication in the http header. You can do this using the Basic Authentication, which is the default behaviour of the Rest applications. I strongly recommend you to read the article Basic Authentication in ASP.NET Web API and see in details how to do it.

Your question is too broad and maybe other users can close it. I think it is good you try to implement and ask for some help posting your code of what you've tried.