IIS 7 UrlReferrer throws exception - asp.net

When I get referrer url, IIS 7 throws an exception. My code like this:
var referrer = Request.UrlReferrer == null ? null : Request.UrlReferrer.AbsoluteUri;
Application throws an ArgumentException with error message,
"Value does not fall within the expected range."
There is no problem in IIS 6.
This exception occurs when the page is navigated with "Response.Redirect"
Application main page has an Response.Redirect method according to role of current user. User main page throws this exception.
How can get Referrer URL in IIS 7.
Thanks,

Ran into similar problem when I tried to access the request object from a System.Threading.Task launched in the request processing.
I'm using the task to reduce response time - in my case most of the processing can be performed after request is sent.
That is, I had something like:
public ActionResult SomeAction()
{
new System.Threading.Task(() => {
// here I used this.Request.UrlReferrer and got weird ArgumenException error
}).Start();
return someActionResultThatDoesntRequireProcessing;
}
I've extracted UrlReferrer (and other this.Request.stuff that I needed) in delayed processing) into a separate "closure" variable (I've chosen them to have the very basic types):
public ActionResult SomeAction()
{
var urlReferrerAbs = this.Request.UrlReferrer.AbsoluteUri;
var clientAddress = this.Request.UserHostAddress;
// save other stuff from the request object
new System.Threading.Task(() => {
// here I used urlReferrerAbs instead of this.Request.UrlReferrer and the error has gone!
}).Start();
return someActionResultThatDoesntRequireProcessing;
}
That worked for me.

Related

How to retrieve JSON data from HttpContent

I'm buildin a console Web API to communicate with a localhost server, hosting computer games and highscores for them. Every time I run my code, I get this charming error:
fail:
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.NotSupportedException: Deserialization of types without a
parameterless constructor, a singular parameterized constructor, or a
parameterized constructor annotated with 'JsonConstructorAttribute' is
not supported. Type 'System.Net.Http.HttpContent'. Path: $ |
LineNumber: 0 | BytePositionInLine: 1.
This is the method I'm using to post to the database. Note that this method is not in the console application. It is in the ASP.NET Core MvC application opening a web browser and listening for HTTP requests (which can come from the console application).
[HttpPost]
public ActionResult CreateHighscore(HttpContent requestContent)
{
string jasonHs = requestContent.ReadAsStringAsync().Result;
HighscoreDto highscoreDto = JsonConvert.DeserializeObject<HighscoreDto>(jasonHs);
var highscore = new Highscore()
{
Player = highscoreDto.Player,
DayAchieved = highscoreDto.DayAchieved,
Score = highscoreDto.Score,
GameId = highscoreDto.GameId
};
context.Highscores.Add(highscore);
context.SaveChanges();
return NoContent();
}
I'm sending POST requests in a pure C# console application, with information gathered from user input, but the result is exactly the same when using Postman for post requests - the above NotSupportedException.
private static void AddHighscore(Highscore highscore)
{
var jasonHighscore = JsonConvert.SerializeObject(highscore);
Uri uri = new Uri($"{httpClient.BaseAddress}highscores");
HttpContent requestContent = new StringContent(jasonHighscore, Encoding.UTF8, "application/json");
var response = httpClient.PostAsync(uri, requestContent);
if (response.IsCompletedSuccessfully)
{
OutputManager.ShowMessageToUser("Highscore Created");
}
else
{
OutputManager.ShowMessageToUser("Something went wrong");
}
}
I'm new to all this HTTP requests stuff, so if you spot some glaring errors in my code, that would be appreciated. Though, the most important question is, what am I missing, and how can I read from the HttpContent object, to be able to create a Highscore object to send to the database?
It seems to be the string jasonHs... line that is the problem, since the app crashed in exactly the same way, when I commented out the rest of the ActionResult method.
Based on your code, we can find that you make a HTTP Post request with a json string data (serialized from a Highscore object) from your console client to Web API backend.
And in your action method, you create an instance of Highscore manually based on received data, so why not make your action accept a Highscore type parameter, like below. Then the model binding system would help bind data to action parameter(s) automatically.
[HttpPost]
public ActionResult CreateHighscore([FromBody]Highscore highscore)
{
//...

Swift 2.0: throw exception within an asynchronous piece of code

I am trying to implement the log in service for an application, and I would like to throw an exception if the response status code is not equal to 200. I am using Alamofire as HTTP networking library.
static func loginWithUsername(username: String, andPassword password: String) throws {
let action = "SmartShoppers/login"
let url = baseUrl + action
Alamofire.request(.POST, url, parameters: ["username": username, "password": password])
.response { request, response, data, error in
if response?.statusCode != 200 {
throw ServiceError.LogInError
}
}
}
This is the ServiceError enum definition:
enum ServiceError: ErrorType {
case LogInError
}
What I want to do deal this exception when it is thrown in a function which is called when a button is pressed. This function is in the ViewController class associated with the ViewController that contains that button. The code that is going to be executed is:
do {
try Service.loginWithUsername(username, andPassword: password)
} catch {
// SHOW AN ALERT MESSAGE
}
Why am I receiving the message Cannot call value of non-function type 'NSHTTPURLResponse'? Is it the correct way to implement this service? If not please help me.
The closure that you are passing to the response method does not include throws in its signature, so you will not be able to throw an exception from within it.
IMO this is not a case where you would want to throw an exception, anyways - a non-200 response code is not an exceptional error / failure, and I wouldn't try to use an exception here as a means of control flow.

How to cancel an upload

I have a asp.net web api page where the user can upload some files. I am using jquery-file-upload. Based on some condition, I want to cancel the upload from the server side but it is not working. No matter what I do, the file always goes to the server before asp.net returns the error. Example, I can keep just this when uploading:
public async Task<HttpResponseMessage> Post(int id, CancellationToken token)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Cant upload");
}
If I put a breakpoint on the return, I can see that it is hitted as soon as the upload starts but I have to wait the upload to end and only then the javascript error handler gets called. Is it not possible to end the request imediatelly, cancelling the upload?
Update 1:
I replaced jquery-file-upload with jquery-form and now I am using ajaxSubmit on my form. This doen't changed anything.
I also tried to implement a DelegatingHandler, like this:
public class TestErrorHandler : DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
//throw new HttpException(403, "You can't upload");
var response = request.CreateResponse(HttpStatusCode.Unauthorized);
response.ReasonPhrase = "You can't upload";
return Task.FromResult<HttpResponseMessage>(response).Result;
}
}
config.MessageHandlers.Add(new TestErrorHandler());
That did not work either.
And I tried to disable buffer on requests:
public class NoBufferPolicySelector : WebHostBufferPolicySelector
{
public override bool UseBufferedInputStream(object hostContext)
{
return false;
}
}
config.Services.Replace(typeof(IHostBufferPolicySelector), new NoBufferPolicySelector());
No game - it still upload all the file before returning the error.
All I need is to cancel a upload request. Is this impossible with web api or I am missing something here?
I had a similar problem, and the only (admittedly ham-fisted) solution I could find to stop the client from uploading the data was to close the TCP connection:
var ctx = Request.Properties["MS_HttpContext"] as HttpContextBase;
if (ctx != null) ctx.Request.Abort();
This works for IIS hosting.

GWT dealing with request error

I have a GWT module and in it I navigate to a different URL via:
Window.Location.assign(url);
The navigated url is then handled by a servlet, up until this point if there was an error it was handle by the resp.sendError methode
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed.");
Which would then navigate to the browsers error page. However I wanted to know is there away I can not navigate to an error page? i.e. I would be able to check in my GWT code if there was an error and then do something? Like resend the request ect.
Thanks!
When you navigate away from your webapplication that's that. Instead of using Window.Location.assign you should make an HTTP request still from your webapplication, for example using RequestBuilder.
Example from the docs mentioned earlier:
import com.google.gwt.http.client.*;
...
String url = "http://www.myserver.com/getData?type=3";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// Couldn't connect to server (could be timeout, SOP violation, etc.)
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
// Process the response in response.getText()
} else {
// Handle the error. Can get the status text from response.getStatusText()
}
}
});
} catch (RequestException e) {
// Couldn't connect to server
}
Note that this will work only if your servlet and webapplication are on the same address (domain, port, protocol), because of Same Origin Policy. If that's not the case, there are still some options, like JSON with padding (which GWT supports via JsonpRequestBuilder).

The remote server returned an error: (405) Method Not Allowed

I was trying to research the problem, but failed, therefore am asking this question here. I have an MVC application calling Web API. One of the methods returns 405 error, and I have no idea why, especially that all of the others methods in the same controller work absolutely fine.
This is how I call this method from MVC end:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format("{0}/api/Account/ArchiveAddress?addressId={1}", uri, addressId));
request.Method = "Get";
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
catch (Exception e)
{
return RedirectToAction("Error", "Error", new { error = e.Message });
}
Where uri is a string:
http://localhost:52599
and addressId is an int
My method on the Web API end looks like this:
[Route("ArchiveAddress")]
public IHttpActionResult ArchiveUserAddress(int addressId)
{
var address = _addressRepo.Find(addressId);
...
As I said, I call many different methods on the API in the exact same way, and they all work fine. Just this one does not want to behave. What might be causing that?
I think you need to decorate your action method (ArchiveUserAddress) with the [HttpGet] attribute or name it something that begins with Get..., e.g. GetArchiveUserAddress. As it stands, it would do match the POST method which means there's no getter hence the error you're getting.

Resources