本文整理汇总了C#中HttpError类的典型用法代码示例。如果您正苦于以下问题:C# HttpError类的具体用法?C# HttpError怎么用?C# HttpError使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HttpError类属于命名空间,在下文中一共展示了HttpError类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Get
/// <summary>
/// GET: api/Widget/{title}. Return search results. Empty string gives zero length result.
/// </summary>
public HttpResponseMessage Get(string title)
{
var bvms = new List<BookViewModel>();
//var results = new List<KeyValuePair<string, List<string>>>(); // Title, authors
var results = new List<WidgetResponseRow>();
if (title != "")
{
try
{
bvms = BookServices.SearchBooks(title);
foreach (var bvm in bvms)
{
results.Add(new WidgetResponseRow(bvm.ISBN, bvm.Title, bvm.Authors.Select(i => i.Value).ToList()));
}
}
catch (DataAccessException)
{
var error = new HttpError("Data access error.");
return Request.CreateResponse(HttpStatusCode.InternalServerError, error);
}
}
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, results);
response.ReasonPhrase = "OK";
return response;
}
示例2: HandleUnauthorizedRequest
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
// http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx
var message = string.Format("No HTTP resource was found that matches the request URI '{0}'.", actionContext.Request.RequestUri);
var error = new HttpError(message);
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.NotFound, error);
}
示例3: Delete
public HttpResponseMessage Delete(string idUser, string emailUser, string passwordUser, string userRegistration, string statusUser)
{
try
{
User user = new User();
DateTime now = DateTime.Now;
#region Atribuir/valorizar modelo
if (!String.IsNullOrWhiteSpace(idUser))
user.IdUser = Convert.ToInt32(idUser);
user.RegistrationDateUser = now;
if (!String.IsNullOrWhiteSpace(userRegistration))
user.ChangeUserUser = Convert.ToInt32(userRegistration);
#endregion
return Request.CreateResponse(HttpStatusCode.OK, user); ;
}
catch (KeyNotFoundException)
{
string mensagem = string.Format("Não foi possível criptografar a entrada: ", emailUser);
HttpError error = new HttpError(mensagem);
return Request.CreateResponse(HttpStatusCode.NotFound, error);
}
}
示例4: GetPropertyValue_GetsDefault_IfPropertyMissing
public void GetPropertyValue_GetsDefault_IfPropertyMissing()
{
HttpError error = new HttpError();
Assert.Null(error.GetPropertyValue<string>("key"));
Assert.Equal(0, error.GetPropertyValue<int>("key"));
}
示例5: ToHttpError
public HttpError ToHttpError(params object[] args)
{
var http = new HttpError();
http["Message"] = string.Format(Message, args);
http["Type"] = Type;
return http;
}
示例6: Get
public HttpResponseMessage Get(string id)
{
try
{
TrataRetorno objRetorno = new TrataRetorno();
List<Indice> Indices = new List<Indice>();
string urlInicial = "http://finance.yahoo.com/webservice/v1/symbols/";
string urlFinal = "/quote?format=xml&view=detail";
string[] stringSeparators = new string[] { "," };
string[] result;
result = id.Split(stringSeparators, StringSplitOptions.None);
foreach (string s in result)
{
XPathDocument doc = new XPathDocument(urlInicial + s + urlFinal);
Indices.Add(objRetorno.TratarRetorno(doc));
}
return Request.CreateResponse(HttpStatusCode.OK, Indices); ;
}
catch (KeyNotFoundException)
{
string mensagem = string.Format("Não foi possível criptografar a entrada: ", id);
HttpError error = new HttpError(mensagem);
return Request.CreateResponse(HttpStatusCode.NotFound, error);
}
}
示例7: Post
public HttpResponseMessage Post(LogOnModel user)
{
try
{
Impersonate.ImpersonateUser(ConfigurationManager.AppSettings["Domain"].ToString(), user.UserName, user.Password);
if (this.ValidateUser(user))
{
FormsAuthentication.SetAuthCookie(user.UserName, true);
return Request.CreateResponse(HttpStatusCode.OK, true);
}
return Request.CreateResponse(HttpStatusCode.OK, false);
}
catch (DirectoryServicesCOMException dse)
{
HttpError error = new HttpError(dse.Message.Replace("\n", " ").Replace("\r", " ").Replace("\t", " "));
return Request.CreateResponse(HttpStatusCode.Unauthorized, error);
}
catch (Exception)
{
throw;
}
finally
{
Impersonate.UndoImpersonation();
}
}
示例8: SerializeError_serializes_httperror
public void SerializeError_serializes_httperror()
{
using (var stream = new MemoryStream())
{
var textWriter = new StreamWriter(stream);
var writer = new JsonTextWriter(textWriter);
var mockInnerException = new Mock<Exception>(MockBehavior.Strict);
mockInnerException.Setup(m => m.Message).Returns("Inner exception message");
mockInnerException.Setup(m => m.StackTrace).Returns("Inner stack trace");
var outerException = new Exception("Outer exception message", mockInnerException.Object);
var error = new HttpError(outerException, true)
{
StackTrace = "Outer stack trace"
};
var jsonSerializer = new JsonSerializer();
var mockIdProvider = new Mock<IErrorIdProvider>(MockBehavior.Strict);
mockIdProvider.SetupSequence(p => p.GenerateId(It.IsAny<HttpError>())).Returns("OUTER-ID").Returns("INNER-ID");
var serializer = new ErrorSerializer(mockIdProvider.Object);
serializer.SerializeError(error, stream, writer, jsonSerializer);
writer.Flush();
var expectedJson = File.ReadAllText("ErrorSerializerTest.json");
var minifiedExpectedJson = JsonHelpers.MinifyJson(expectedJson);
var output = System.Text.Encoding.ASCII.GetString(stream.ToArray());
output.Should().Be(minifiedExpectedJson);
}
}
示例9: OnException
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is FormValidationException)
{
var exception = context.Exception as FormValidationException;
var fieldErrors = exception.FieldErrors
.Select(x => "{ Field: " + x.Item1 + ", Error: " + x.Item2 + " }");
var error = new HttpError(exception.Message)
{
{ "Type", "FormValidationException"},
{ "FieldErrors", fieldErrors}
};
context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error);
}
else if (context.Exception is DomainException)
{
var exception = context.Exception as DomainException;
var error = new HttpError(exception.Message)
{
{ "Type", "DomainException"},
};
context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error);
}
else
{
var error = new HttpError("An unknown error has occurred.");
context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error);
}
}
示例10: Invoke
public async override Task Invoke(IOwinContext context)
{
try
{
await Next.Invoke(context);
}
catch(Exception ex)
{
_logger.Error("Last chance exception caught.", ex);
var headers = context.Request.Headers;
// if server accepts json - just return json error
if (headers.ContainsKey("Accept") && headers["Accept"].Contains("application/json"))
{
var includeDetail = context.Request.LocalIpAddress == context.Request.RemoteIpAddress;
var message = new HttpError(ex, includeDetail);
var serializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
context.Response.StatusCode = 500;
context.Response.Write(JsonConvert.SerializeObject(message, serializerSettings));
}
// otherwise - let the owin to return html
else
{
throw;
}
}
}
示例11: ToODataInnerError
private static ODataInnerError ToODataInnerError(HttpError httpError)
{
string innerErrorMessage = httpError.GetPropertyValue<string>(HttpErrorKeys.ExceptionMessageKey);
if (innerErrorMessage == null)
{
string messageDetail = httpError.GetPropertyValue<string>(HttpErrorKeys.MessageDetailKey);
if (messageDetail == null)
{
HttpError modelStateError = httpError.GetPropertyValue<HttpError>(HttpErrorKeys.ModelStateKey);
return (modelStateError == null) ? null
: new ODataInnerError { Message = ConvertModelStateErrors(modelStateError) };
}
else
{
return new ODataInnerError() { Message = messageDetail };
}
}
else
{
ODataInnerError innerError = new ODataInnerError();
innerError.Message = innerErrorMessage;
innerError.TypeName = httpError.GetPropertyValue<string>(HttpErrorKeys.ExceptionTypeKey);
innerError.StackTrace = httpError.GetPropertyValue<string>(HttpErrorKeys.StackTraceKey);
HttpError innerExceptionError = httpError.GetPropertyValue<HttpError>(HttpErrorKeys.InnerExceptionKey);
if (innerExceptionError != null)
{
innerError.InnerError = ToODataInnerError(innerExceptionError);
}
return innerError;
}
}
示例12: Get
// GET /api/projects/4/researchitems/5
public virtual HttpResponseMessage Get(int projectId, int researchItemId)
{
var researchItems = new List<ResearchItem>();
var project = new Project();
try
{
// Verify that the user is the owner of project and research item.
project = _projectRepository.GetByUser(projectId, User.Identity.Name);
if (project == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Project not found for user " + User.Identity.Name + ".");
}
var researchItem = _researchItemRepository.GetByUser(researchItemId, User.Identity.Name);
if (researchItem == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Research item not found for user " + User.Identity.Name + ".");
}
researchItems.Add(researchItem);
}
catch (Exception ex)
{
var error = new HttpError("Error getting research item: " + ex.Message) { { "Trace", ex.StackTrace } };
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error);
}
var researchItemDto = new ResearchItemDto()
{
Meta = new ResearchItemMeta() { NumberResearchItems = researchItems.Count(), ProjectName = project.Name },
ResearchItems = researchItems
};
return Request.CreateResponse<ResearchItemDto>(HttpStatusCode.OK, researchItemDto);
}
示例13: ConvertModelStateErrors
// Convert the model state errors in to a string (for debugging only).
// This should be improved once ODataError allows more details.
private static string ConvertModelStateErrors(HttpError error)
{
StringBuilder builder = new StringBuilder();
foreach (KeyValuePair<string, object> modelStateError in error)
{
if (modelStateError.Value != null)
{
builder.Append(modelStateError.Key);
builder.Append(" : ");
IEnumerable<string> errorMessages = modelStateError.Value as IEnumerable<string>;
if (errorMessages != null)
{
foreach (string errorMessage in errorMessages)
{
builder.AppendLine(errorMessage);
}
}
else
{
builder.AppendLine(modelStateError.Value.ToString());
}
}
}
return builder.ToString();
}
示例14: Post
public HttpResponseMessage Post(LogOnModel model)
{
try
{
if (this.ValidateUser(model))
{
FormsAuthentication.SetAuthCookie(model.UserName,true);
return Request.CreateResponse(HttpStatusCode.OK, true);
}
return Request.CreateResponse(HttpStatusCode.OK, false);
}
catch (DirectoryServicesCOMException dse)
{
HttpError error = new HttpError(dse.Message.Replace("\n", " ").Replace("\r", " ").Replace("\t", " "));
return Request.CreateResponse(HttpStatusCode.Unauthorized, error);
}
catch (Exception ex)
{
HttpError error = new HttpError(ex.Message.Replace("\n", " ").Replace("\r", " ").Replace("\t", " "));
EventLog log = new EventLog();
log.Source = "Jaguar_Mobile";
log.WriteEntry(ex.Message);
return Request.CreateResponse(HttpStatusCode.InternalServerError, error);
}
}
示例15: Get
public HttpResponseMessage Get(int id)
{
var periodDetialsRequestViewModel = new PeriodDetailsRequestViewModel() { PeriodId = id };
var serviceResponse = _periodDetailsPresenter.GetListingsByGroupId(periodDetialsRequestViewModel);
HttpResponseMessage httpResponse;
switch (serviceResponse.StatusCode)
{
case PeriodicTableStatusCodes.Success:
httpResponse = Request.CreateResponse(HttpStatusCode.OK, serviceResponse);
break;
case PeriodicTableStatusCodes.Error:
var internalServiceError = PeriodicTableServerExceptionResponse.GetInternalServiceError();
httpResponse = Request.CreateResponse(HttpStatusCode.InternalServerError, internalServiceError);
break;
default:
var error = new HttpError(GetCorrectErrorMessage(serviceResponse.StatusCode))
{
{"ErrorCode", serviceResponse.StatusCode}
};
httpResponse = Request.CreateErrorResponse(HttpStatusCode.BadRequest, error);
break;
}
return httpResponse;
}