call a regular MVC controller method from a webapi2 service - c#

Given an MVC controller method, that builds and returns a PDF.
[HttpGet]
[Route("pdf/{acc}/{sign}")]
public async Task<ActionResult> Download(string acc, string sign)
{
... // omitted some irrelevant detail.
var html = this.View("Letter", model).Capture(this.ControllerContext);
byte[] pdf = this.CreatePdfFromHtml(html);
return this.File(binary, "application/pdf", file);
}
The Capture extension method captures the html output, which is then returned as a file.
I need to execute the above method (or something close) in the below webapi2 method.
I need the credentials and other login state to be present. The webapi and MVC requests are within the same application that uses cookies for security.
[HttpPost]
[Route("generate")]
public int Generate(MyRequestModel request)
{
byte[] pdf = ... // how do i get the file above??
}

You should either request the MVC action via HttpClient or simply factor out the PDF creation into a helper class that both your MVC and Web Api actions can reference.
With the first method, you would need to some how authenticate the request, which is going to be a bit difficult to do with an MVC action. MVC uses a multi-step authorization: sign in, verify, set cookie, redirect. You would have to follow those same steps in order to get a cookie set via HttpClient. Think of it as a little mini-browser. Web Api, on the other hand, simply accepts an Authorization header, since API requests are idempotent.
The easiest and most straight-forward route, especially since both your MVC and Web Api reside in the same application, would be to simply factor out the PDF creation code into a helper class. Your MVC and Web Api actions, then, can simply just call some method on that class to get the PDF, reducing code duplication.

Related

Use request body for HTTP-DELETE method (ASP.NET Core WebAPI)

According to the RFC7231 standard:
A payload within a DELETE request message has no defined semantics;
sending a payload body on a DELETE request might cause some existing
implementations to reject the request.
In my example I am using ASP.NET Core WebApi and I would like to use a request body for an HTTP delete method. Fortunately it works, but I can't find any documentation that confirms that a request body is allowed / supported in ASP.NET Core WebApi.
[HttpDelete("{id}")]
public async Task<ActionResult<bool>> Delete(int id, [FromBody] AnyRequestBodyType body)
{
// Do some checks with the param "body" here.
// If everything is OK, the resource will be deleted.
// Otherwise, I want to return an HTTP 4xx error.
}
Can I be sure that the API will work in future ASP.NET Core WebAPI releases?
Do you have any other suggestions? I don't want to pass the parameter via query string because the AnyRequestBodyType is "complex" and a url-encoded request would no longer be readable or "manually executeable".

Can a asp.net MVC controller class return Action Method and Json both?

Thanks for your time , I have a simple question, in an asp.net MVC application, inside controllers is it possible that along with some methods returning View (ActionMethods) other could act as (or return) Json as a Web API (could be called from external apps).
Just trying to do a proper separations, hence trying to understand.
Thanks much.
You can make an action function like an API. Try something like the this.
// Controller/Action
[HttpGet]
public ActionResult IAmSpecial()
{
if (Request.IsAjaxRequest())
{
string[] objects = new string[] { "Foo", "Bar" };
return Json(objects);
}
return View();
}
This will return the IAmSpecial view if you browse to {domain}/{Controller}/IAmSpecial while it will return a JSON result if you use an AJAX Http Get request on the same url.
while it is possible to have controller methods which return Json data only, there are a number of considerations when you want to expose that data outside of the UI app.
Since you have an MVC app, I expect you have users and a way to login. Your controllers would more than likely be secured in some way, which works for the internal users of the application. Now you want to add one method which effectively becomes an API, available outside of the application and calls to it will have to be authenticated somehow.
What I would suggest is to split this up. You can create a separate project, which is a WebAPI one, in the same solution. The code which prepares the data can live in a class library you can then reference in both your MVC and WebAPI projects.
Your MVC app can call it and then return a view with that data, the WebAPI calls it and simply returns the data. You can now decide on a way of securing your API, maybe using Identity Server or some other way and you can keep adding things to it, without affecting the UI layer.
Your second option is to make the MVC app use the API when it needs to retrieve data, so both your public clients and UI use the same thing.
Whichever option you use, the idea is to not duplicate anything and at the same time provide the security layers you need.

Problems trying to return the view with an API controller

I'm implementing a REST Web API. I'm using the examples from Adam Freeman's Pro ASP.NET MVC5 as a starting point but adapting it into the Web API way of doing it.
The below is my code:
public class AdminController : ApiController
{
private IUserRepository _repository;
public AdminController(IUserRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
return View(_repository.Users);
}
}
In the book, AdminController implemented Controller not ApiController, but if I do that then I get errors about there being no parameterless constructor. I need the constructor to take parameters so that I can inject the dependencies. So that's why I changed to ApiController but now it won't recognise View.
What do I need to use instead of View for an ApiController?
I did find this question but the answer was basically "you don't need to use an ApiController here, just use Controller" so that didn't help me.
You are having two different problems. Let's solve them separately.
1. Do I need to use ApiController or Controller?:
Someone already answered this here: Difference between ApiController and Controller in ASP.NET MVC.
The first major difference you will notice is that actions on Web API
controllers do not return views, they return data.
ApiControllers are specialized in returning data. For example, they
take care of transparently serializing the data into the format
requested by the client.
So, if you want to return a View you need to use the simple ol' Controller. The WebApi "way" is like a webservice where you exchange data with another service (returning JSON or XML to that service, not a View). So whenever you want to return a webpage (View) for a user you don't use the Web API.
In other words, the Web API is about returning data to another service (to return a JSON or XML), not to a user.
2. But if I use Controller then I get "parameterless constructor" errors.
Okay, now we've got to your real problem. Don't try to reinvent the wheel and fight with ASP.NET about doing dependency injection! A tool already exists to resolve dependency injection and sort out the "parameterless constructor" error: Ninject.
If you're already using Ninject and still getting that error, you're doing something wrong with Ninject. Try to repeat the installation and configuration steps, and see some tutorials or questions about parameterless error with Ninject use
An API controller is a controller which provides a RESTful response. You cannot return a view from it. Instead of doing that, consider returning a response (values) which forces the client that asks for an action to redirect to another controller (passing arguments if necessary) to return a view.
Your case does not look like you need an API; in this case just try this (change what you inherit):
public class AdminController : Controller
{
private IUserRepository _repository;
public AdminController(IUserRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
return View(_repository.Users);
}
}
I will try to explain what an API should do anyway. A web API should return just information. An HTTP response about what the action should do.
For example, to create a new customer, an API should have a method (decorated with POST) to get information from a client application (could be anything: web, windows, mobile, windows service, etc.). This information should be processed by the API (or other layers in a possible architecture) and return an HTTP status code, for example 200 - OK if it was fine or 400 - Bad Request if an error happened. So, when I said you should consider returning information, you could just return a DTO object to provide a result.
Both types of project use MVC principles, but they are used in a different context. Take a look at these articles:
Web Api 2.0 Tutorial
Difference between MVC and WEB API
Also take a look at the ASP.NET website about how they work:
ASP.NET WEB API
ASP.NET MVC
Use Controller to render your normal views. ApiController action only return data that is serialized and sent to the client.
But still you want to render view from APIcontroller, then there may be a another way, click on below link for reference :
https://aspguy.wordpress.com/2013/09/10/web-api-and-returning-a-razor-view/

Getting an external webapi url given a list of routes it uses

I have a WebAPI (v1) app that I'm creating. It has various custom routes, that all work fine.
I have a client application I'm creating (which is MVC+webapi itself), which calls the webapi app using HttpClient. Currently I've hard-coded the urls to call, but I'd like to calculate them automatically based on a list of routes (which I could put in a shared library).
So, in my shared library I would have a list of a class that contains Name, RouteTemplate and Defaults, which in my webapi I'd iterate through that list to create my routes and in the client application i'd somehow use to calculate the url to get HttpClient to call.
How do I calculate the url to call an external webapi app from a client app (that could itself have its own routing)?
So since I know what you want, I give it a try
So I assume you have a routes table for your api which has the colums: route, controller, action, verb. An example row could be:
/foo/bar/{id}, fooController, barAction, GET
In the client app you have access to that data so you can compose an url of that when you know which controller and action to call with which verb. The combination of controller, action and verb is unique in mvc.
So you filter on fooController , barAction and verb GET and you get the route. You replace {id} with your id parameter and you have an url.

How to compress ASMX Data With String JSON Response(C# Web Service)

I'm calling my webservice from an Android application one after another. And at every call it returns with almost 3.5KB data.
I'm using JavascriptSerializer class to serialize and convert to JSON string my Dictionary<string,string> or Dictionary<string,string>[] objects. (Especially Dictionary<string,string>[])
Is there a way to reduce this amount of data. It's so much.Or am i doing something wrong?
Thanks..
Script files loaded via an HTML element within a browser can only be retrieved via HTTP GET verb requests.
By default ASP.NET AJAX's web services layer does not allow web methods to be invoked via the HTTP GET verb. For example, assume a developer writes a web service method like below:
[WebMethod]
public StockQuote[] GetQuotes(string symbol) {
}
ASP.NET will only allow the above GetQuotes method to be called via the HTTP POST verb, and will reject all attempts to invoke the method via an HTTP GET verb.
To make an ASP.NET AJAX web-method callable via HTTP GET-access, a developer must explicitly attribute each method using ASP.NET's ScriptMethod attribute (and set the UseHttpGet property to true):
[WebMethod]
[ScriptMethod(UseHttpGet=true)]
public StockQuote[] GetQuotes(string symbol) {
}
for more info please refer below link
http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx

Categories