get files url reques in action of mvc controller - c#

I want get file url request in controller .
when come this request
http://localhost:4616/Images/Users/mohammadhossein21#gmail.com/hm2.jpg
or this request
http://localhost:4616/Images/Users/mohammadhossein21#gmail.com/4230.pdf
I can get this request in The following action of Images Controller
public ActionResult Users(string Email, string Name)
{
string subPath1p = Directory.GetParent(Server.MapPath("~/")).Parent.FullName + "\\SUPPORT_USERSFILES\\" + Email+"\\"+Name+".pdf";
return File(subPath1p, "application/pdf");
}

You should customize routing: see here or here for example.

Instead of ActionResult, use FileResult as return type.

Related

Routing a redirect URL in Web Api .Net

I am working on Github api Oauth.
The main problem is to match callback URl with method in Web Api
[HttpGet]
[Route("api/values/callback/{code}&{state}")]
public JsonResult Get (string code, string state)
{
var s = User.Claims;
return new JsonResult(s);
}
In StartUp file:
options.CallbackPath = new PathString("/api/values/callback/");
Redirect in URL that should match an action in service
http://localhost:5000/api/values/callback/?code=b1b0659f6e0&state=CfDJ8Ir-xT
So, I can not build rout which has pattern /?param1&param2
Here is redirect URL that should match :
Would be glad for help :)
You can use [FromQuery] to get values from the query string.
[HttpGet]
[Route("api/values/callback")]
public JsonResult Get([FromQuery]string code, string state)
{
string s = "code:" + code + " state:" + state;
return new JsonResult(s);
}
Test
If you're using OidClient you can use the following to inject the service to the method and get the querystring to process.
// route method here
public async Task<ActionResult> ProcessCallback([FromServices] HttpListenerRequest request){
...
// generate the options using `OidcClientOptions`
var client = new OidcClient(options);
var result = await client.ProcessResponseAsync(request.QueryString.ToString(), null);
...
}
I would suggest to edit the route to api/values/callback/code={code}&state={state} .

How to Add Uri to the Created(Status Code 201) of a Post Request

i just started learning asp.net core api and i'm trying to make a post request from Postman. I want to return a status code of 201 upon post and return the Uri of the newly posted data as the location. Below is my controller code
[HttpPost]
public ActionResult CreateMake([FromBody]MakeResource makeresource)
{
if (!ModelState.IsValid) {
return BadRequest(ModelState) ;
}
var makes = mapper.Map<MakeResource, Make>(makeresource);
_makes.AddMake(makes);
makeresource.Id = makes.Id;
return Created(new Uri(Request.Path, UriKind.Relative), makeresource);
}
I get an error
System.UriFormatException: 'Invalid URI: The format of the URI could
not be determined.'
and I guess it has to do with the Uri(Request.Path).
In Asp.net web api, I would implement it as return Created(new Uri(Request.Uri + "/" + makes.Id), makeresource); and the action type would be IHttpActionResult instead of ActionResult as shown in my controller but it doesn't work that way in asp.net core.
Any assistance on how to solve this issue would be needed.
Thanks.
I just want to put this here, incase anybody needs it in the future.
I got the answer i used from What is the ASP.NET Core MVC equivalent to Request.RequestURI?
I solved my issue by replacing (Request.Path, UriKind.Relative) with as (Request.GetEncodedUrl()+ "/" + makes.Id) seen below:
return Created(new Uri(Request.GetEncodedUrl()+ "/" + makes.Id), makeresource);

How to pass a URL as a query string parameter in MVC

does anyone know how to pass a URL as a query string parameter and then get the URl in HttpGet method as a parameter ?
Thanks so much for all the answers. Finally I got it sorted. Please refer to my fix below:
[Route("api/[controller]")]
public class UrlController : Controller
{
[HttpGet("{*longUrl}")]
public string ShortUrl(string longUrl)
{
var test = longUrl + Request.QueryString;
return JsonConvert.SerializeObject(GetUrlToken(test));
}
just like this?
current url with UrlEncode
[HttpGet]
public ActionResult Index(string url = null)
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
HttpUtility.UrlEncode should do the job for you
404 might be because the application is not in running mode
host you application and try it in local it should be working as needed
i was trying as http://localhost:11331/Home/?id=http%3A%2F%2Flocalhost%3A11331%2F
and everything is working fine even the redirection to the launch screen
or else post the complete URL you are getting so that i can help you

Redirect to referrer URL but add something to the querystring

Using ASP.Net MVC, I'm posting off to an action (where I'm then adding an email address to a DB table etc.)
I need to re-direct back to the referrer URL but also need to add something to the querystring of the referrer URL. This action can be called from many places, so I can't redirect to an action in the current controller.
How do I re-direct to the referrer and add something to the query string (bearing in mind that the referrer might already have query string values that I'll need to preserve).
[HttpPost]
public ActionResult MyAction(MyModel model)
{
//Do stuff.
return new RedirectResult(Request.UrlReferrer.ToString()); // + query string value?
}
Thanks!
Use an UriBuilder and HttpUtility.ParseQueryString:
[HttpPost]
public ActionResult MyAction(MyModel model)
{
//Do stuff.
UriBuilder uriBuilder = new UriBuilder(Request.UrlReferrer);
NameValueCollection query = HttpUtility.ParseQueryString(uriBuilder.Query);
query.Add("myparam", "something");
uriBuilder.Query = query.ToString();
return new RedirectResult(uriBuilder.Uri);
}
try this
string url = Request.UrlReferrer.ToString();
if(url.Contains("?"))
url += "&newparam=something";
else
url += "?newparam=something";
return new RedirectResult(url);

ASP.NET MVC-2 How can you recieve a POST from another website?

If another website is making a POST to my ASP.NET MVC 2 site, how can I capture it? Do I need to do anything to the routes?
eg The other site does this:
string url = "https://mvc2-site.com/TestReceive"; // that's my site's controller action
NameValueCollection inputs = new NameValueCollection();
inputs.Add("SessionId", "11111");
System.Net.WebClient Client = new WebClient();
byte[] result = Client.UploadValues(url, inputs);
How do I receive that POST on my site? I have tried:
public ActionResult TestReceive(FormCollection fc) {} // doesn't get hit
public ActionResult TestReceive(string SessionId) {} // method gets hit but session id is null
public ActionResult TestReceive()
{
var param = ControllerContext.RouteData.Values["parameter"].ToString(); // Values["parameter"] is null
}
I do not control the other site and it must be a POST (not a webservice or anything else)
As another twist they will POST around 10 variables, but some are optional, so they may not be in the POST data.
[HttpPost]
public ActionResult TestReceive(string sessionId)
{
...
}
Also as there's no controller specified in the url you should make sure that the controller that contains this action is the default controller in the routes.

Categories

Resources