- Remove From My Forums
-
Question
-
Hi
I’ve created a WCF Service Application, when I click to F5 it works fine, but when I’m publishing in IIS I got this Error
Server Error in ‘/’ Application.
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: It is an error to use a section registered as allowDefinition=’MachineToApplication’ beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.
Source Error:
Line 16: </serviceBehaviors> Line 17: </behaviors> Line 18: <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> Line 19: </system.serviceModel> Line 20: <system.webServer>
Source File: C:inetpubwwwroothserver2web.config Line:
18Please can anybody tell me what to do to correct this error
or if i host this site to an public IP, does it will work fine to connect with it through my client app
Answers
-
Hi Bayar,
I think the error message has already pointed you the potential cause:
=======================
Parser Error Message: It is an error to use a section registered as allowDefinition=’MachineToApplication’ beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.
========================and based on the following settings when you publish to IIS:
=================
Site/application: Default web site/myservice
unchecked: mark as IIS application on destination
checked: leave extra files on destination (do not delete)=================
the problem is likely caused by the iis virtual directory in which you published your service is not marked as «Application». So you can check the «mark as IIS application on destination» option when publishing and test it again.
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
-
Edited by
Wednesday, March 7, 2012 6:39 AM
-
Marked as answer by
Yi-Lun Luo
Friday, March 9, 2012 9:01 AM
-
Edited by
- Remove From My Forums
-
Question
-
Hi All,
I have developed RESTful service that communicates with SQL Azure database. Everything works as expected on my local DEV environment.
But once I deployed on Windows Azure, it started giving below error. Any help on this is appreciated, I have tried all customerror mode Off/On/RemoteOnly without any luck.
<!-- Web.Config Configuration File --> <configuration> <system.web> <customErrors mode="Off"/> </system.web> </configuration>
Notes:
The current error page you are seeing can be replaced by a custom error page by
modifying the «defaultRedirect» attribute of the application’s
<customErrors> configuration tag to point to a custom error page
URL.<!-- Web.Config Configuration File --> <configuration> <system.web> <customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/> </system.web> </configuration>
Harit K
Answers
-
Hi,
Does it happen when you access .svc in browser or when you access the RESTful service? The first step to troubleshoot WCF issue is to configure WCF tracing:
http://msdn.microsoft.com/en-us/library/ms733025.aspx
You can RDP to the cloud VM and
check out the trace log. The log can give you more insights as to what the problem is. Please let me know the detailed information about the error that you find in the log if this problem still cannot be resolved.
Allen Chen [MSFT]
MSDN Community Support | Feedback to us
-
Edited by
Friday, September 21, 2012 5:58 AM
-
Marked as answer by
Jiang Yun
Thursday, September 27, 2012 9:54 AM
-
Edited by
I created a simple wcf service that exposes a GetData method. It’s actually the template created when you create a new wcf project.
I added the application to iis server, so it can be accessed from the outside, like this: http://192.168.0.100/TFSWrapper/Service1.svc
I used a generic soap client to send a request to the GetData method. This is the soap request that was generated:
<?xml version="1.0" encoding="utf-16"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetData xmlns="http://tempuri.org/" />
</soap:Body>
</soap:Envelope>
Here is the soap response:
<?xml version="1.0" encoding="utf-16"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetDataResponse xmlns="http://tempuri.org/">
<GetDataResult>You entered: 87</GetDataResult>
</GetDataResponse>
</s:Body>
</s:Envelope>
By the way, I removed the parameter from the method and hardcoded a return value.
As you can see, everything works as it should.
Next, I created a Titanium client that calls the same service. I used the exact soap request as above, just to make sure.
Basically I did this:
var s='<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetData xmlns="http://tempuri.org/" /></soap:Body></soap:Envelope>';
//xhr.send(config.envelopeBegin+body+config.envelopeEnd);
xhr.send(s);
When this is sent, the server is returning a «500 internal server error» response together with the following fault string:
The message with Action ‘http://tempuri.org/GetData’ cannot be
processed at the receiver, due to a ContractFilter mismatch at the
EndpointDispatcher. This may be because of either a contract mismatch
(mismatched Actions between sender and receiver) or a binding/security
mismatch between the sender and the receiver. Check that sender and
receiver have the same contract and the same binding (including
security requirements, e.g. Message, Transport, None).
At first I used the titanium soap api to create the request xml, but I was getting the same error. I though it was a problem with how that is created, so that’s why I hard-coded a request (that works), but still no luck.
- Remove From My Forums
-
Вопрос
-
Добрый день, господа. Подскажите, куда копать.
Windows Server 2008 R2 32 bit.
В IIS развернут узел, — сайт web-forms,с аутентификацией по сертификату.
Есть ссылка на wcf, от которой получает данные.
При запускe на iisexpress через VS2013 в режиме отладки — все хорошо. После публикации и размещения на вышеуказанном сервере — вот такая ошибка:
Ошибка сервера в приложении ‘/’.
An error occurred when verifying security for the message.
Описание: Необработанное исключение при выполнении текущего веб-запроса. Изучите трассировку стека для получения дополнительных сведений о данной ошибке и о вызвавшем ее фрагменте кода.
Сведения об исключении: System.ServiceModel.FaultException: An error occurred when verifying security for the message.
Ошибка источника:
Необработанное исключение при выполнении текущего веб-запроса. Информацию о происхождении и месте возникновения исключения можно получить, используя следующую трассировку стека исключений.
Трассировка стека:
[FaultException: An error occurred when verifying security for the message.] [MessageSecurityException: Незащищенное или неправильно защищенное сообщение об ошибке было получено от другой стороны. Код ошибки и описание см. внутреннее исключение.] System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +10818447 System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +336 Service_portal.ServiceReference.IHotLine.GetData(String ProcName, CustomParams[] _params, String DBname) +0 Service_portal.ContactClass.AddParams(String name, String value, String proc, String dbnum) +276 Service_portal.ControlDistionary.Page_Load(Object sender, EventArgs e) +59 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51 System.Web.UI.Control.OnLoad(EventArgs e) +92 System.Web.UI.Control.LoadRecursive() +54 System.Web.UI.Control.LoadRecursive() +145 System.Web.UI.Control.LoadRecursive() +145 System.Web.UI.Control.LoadRecursive() +145 System.Web.UI.Control.LoadRecursive() +145 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
-
Перемещено
26 марта 2015 г. 11:36
-
Перемещено
Ответы
-
Здравствуйте,
Похоже на ошибку с WCF, как одна из возможных причин, если время клиента и сервера отличается более чем на 10 минут, то не удастся пройти
проверку безопасности .
Best Regards, Andrei …
Microsoft Certified Professional-
Предложено в качестве ответа
Tomas Lilov
26 марта 2015 г. 12:30 -
Помечено в качестве ответа
Иван ПродановMicrosoft contingent staff, Moderator
31 марта 2015 г. 7:50
-
Предложено в качестве ответа
#c# #wcf
#c# #wcf
Вопрос:
Я создаю службу WCF для хранения некоторых данных в Xamarin.Я создаю приложение Forms. Я развернул эту службу в службе приложений Azure. При переходе к URL-адресу я получаю следующую ошибку:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /EventWCFService.svc
Кодирование службы WCF:
public class EventWCFService : IEventWCFService
{
private static IEventService _eventService = new EventService(new EventRepository());
public void AddEvent(Event @event)
{
try
{
if (String.IsNullOrWhiteSpace(@event.EventTitle) || @event == null)
{
throw new FaultException("Event name is required");
}
_eventService.AddEvent(@event);
}
catch (Exception exception)
{
throw new FaultException($"Whoops... Something has gone wrong {exception.Message}");
}
}
public IList<Event> GetAllEvents()
{
return _eventService.GetAllEvents();
}
}
Мой проект WCF также содержит репозитории и службы:
IEventWCFService:
[ServiceContract]
public interface IEventWCFService
{
[OperationContract]
IList<Event> GetAllEvents();
[OperationContract]
void AddEvent(Event @event);
}
Web.Config:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.8" />
<httpRuntime targetFramework="4.8"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
Вещи, которые я пробовал:
- Прежде всего, я попытался зайти в свойства и создать виртуальный каталог — это не сработало и не решило проблему.
- Я попытался установить для «Конкретной страницы» значение пустой — это все равно не решило проблему.
- Я попытался создать новый сервис приложений — и все равно столкнулся с проблемой.
Я совсем новичок в WCF — так что прошу прощения, если это может быть ошибкой новичка. Я следую курсу Pluralsight, и я неплохо справлялся до части развертывания Azure.
Комментарии:
1. это чисто проблема WCF, она не имеет ничего общего с Xamarin
2. извиняюсь за это @Jason … Я, должно быть, запутался
Ответ №1:
Я решил эту проблему, создав и развернув новую службу приложений Azure непосредственно с портала Azure, а не из самой Visual Studio. Затем я развернул службу WCF непосредственно из существующей службы приложений, которую я только что создал.
So, here is the issue I encountered today. I have a solution that is using WCF service to communicate. My WCF service is hosted in a web site (web application project). I was getting error from my client, stating that connection was forcibly closed by the server. I could not figure out why even though I configured behavior to «includeExceptionDetailInFaults». So, here is the solution that I found.
I added the following to web.config file to web site that hosts WCF service.
<system.diagnostics>
<sources>
<source name=»System.ServiceModel»
switchValue=»Information, ActivityTracing»
propagateActivity=»true»>
<listeners>
<add name=»traceListener»
type=»System.Diagnostics.XmlWriterTraceListener»
initializeData= «c:Traces.svclog» />
</listeners>
</source>
</sources>
</system.diagnostics>
Voila. I ran the process again, double-clicked on trace log that opened in a viewer. I was informed that I forgot to add Serializable attribute to my class I was sending across the wire.
What an easy solution! What a greate WCF feature as well – you can debug service even in production without changing code – just change configuration file. The same trick works in Windows hosted WCF services – just add the same stuff to app.config.
What If There’s No Error Handling?
Suppose I write a WCF web service with no try-catch blocks and no error handling. What happens when my web service throws an exception? Since I don’t have any error handling, WCF catches the exception for me. It sends the client (the program that called my web service) a FaultException with the following message:
«The server was unable to process the request due to an internal error.»
Whenever there’s an unhandled exception, that’s all the information the client gets. WCF doesn’t send the client the exception message or the stack trace or any of the other information that was contained in the exception.
There are a number of reasons why WCF does this. One reason is that the Exception class is specific to .Net. WCF was designed to make web services that can be called by anyone, including clients that are not written in .Net. The client program can be written in Java or PHP or a variety of other languages. So WCF doesn’t assume that the clients were written in .Net, and it doesn’t send them .Net specific responses.
Another reason WCF doesn’t send the client more information is that this might not be safe. It’s not safe to provide the stack trace to anyone that may call. Detailed error messages are also risky. For example, it’s not safe to inform the caller that the database insert failed because user name «andrew.fenster» is already in use. The safer practice is to write this information to an error log and provide much less detailed error information to the caller.
Providing More Information With FaultExceptions
A bare FaultException may be safe, but it doesn’t provide enough information. I may not want to pass the full stack trace, but I want to provide at least basic information about what went wrong. WCF provides multiple ways to do this.
The FaultException class itself includes several ways to provide more information. The FaultException class includes these constructors (among others):
- public FaultException(string reason);
- public FaultException(string reason, FaultCode code);
- public FaultException(FaultReason reason);
- public FaultException(FaultReason reason, FaultCode code);
The simplest way to provide information is the first of these:
- try
- {
- }
- catch (Exception ex)
- {
- myLogger.LogException(ex);
- throw new FaultException(«Your request timed out. Please try again later.»);
- }
The client can capture the FaultException and read the message as follows:
- try
- {
- }
- catch (FaultException ex)
- {
- Console.WriteLine(ex.Message);
- }
As you can see from the FaultException constructors, you can create a FaultException with a string, a FaultCode, a FaultReason or some combination of these.
The FaultReason class lets you provide the same error message in multiple languages. If you look at the list of FaultException constructors, you will see that you can either provide an error message in a string or a collection of error messages in a FaultReason. You don’t need both.
A FaultCode allows you to provide a code (a string) to tell the client what went wrong. For example:
- try
- {
- }
- catch (Exception ex)
- {
- myLogger.LogException(ex);
- FaultCode code = new FaultCode(«Invalid Operation»);
- throw new FaultException(«Customer name cannot be null.», code);
- }
The client can catch the FaultException and read the FaultCode as follows:
- try
- {
- }
- catch (FaultException ex)
- {
- Console.WriteLine(«FaultCode: « + ex.Code);
- Console.WriteLine(«Message: « + ex.Message);
- }
The FaultException<T> class
The FaultException class gives you several ways to inform the client about what went wrong. Sometimes, however, you may want more.
The FaultException<T> class is derived from the FaultException class. As with the FaultException class, you can pass in some combination of string, FaultCode and FaultReason. You can also pass in some additional value T. T can be a value or an entire class object. For example, you could define your own error class:
- [DataContract]
- public class ErrorMessage
- {
- private Guid ticketNumber;
- [DataMember]
- public Guid TicketNumber
- {
- get { return ticketNumber; }
- set { ticketNumber = value; }
- }
- [DataMember]
- public string Message
- {
- get { return «An error has occurred. For more information,
- call us and tell us your ticket number.»; }
- } public ErrorMessage(Guid newTicket)
- {
- ticketNumber = newTicket;
- }
- }
You could use this as follows:
- try
- {
- }
- catch (Exception ex)
- {
- Guid ticket = myLogger.LogException(ex);
- ErrorMessage message = new ErrorMessage(ticket);
- throw new FaultException<ErrorMessage>(message);
- }
The client can catch this FaultException as follows:
- try
- {
- }
- catch (FaultException<ErrorMessage> ex)
- {
- Guid ticket = ex.Detail.TicketNumber;
- string message = ex.Detail.Message;
- }
Of course you could also throw in a FaultCode or a FaultReason, since FaultException<T> is derived from FaultException. FaultException<T> includes these constructors:
- public FaultException(T detail);
- public FaultException(T detail, string reason);
- public FaultException(T detail, FaultReason reason);
- public FaultException(T detail, string reason, FaultCode code);
- public FaultException(T detail, FaultReason reason, FaultCode code);
When you use the FaultException<T> class, T can be any type, provided in can be serialized. If you are going to use your own custom class, you should define a DataContract for your class, as shown above.
FaultContracts
If you are going to use the FaultException<T> class, you need to create a FaultContract. The FaultContract tells the client program what type of Faults each method can throw. For example:
- [ServiceContract]
- interface IMyService
- {
- [OperationContract]
- [FaultContract(typeof(ErrorMessage))]
- int DoSomething();
- }
This FaultContract informs the client that when it calls DoSomething( ) it may receive a fault of type FaultException<ErrorMessage>.
You can specify more than one fault type. For example:
- [ServiceContract]
- interface IMyService
- {
- [OperationContract]
- [FaultContract(typeof(ErrorMessage))]
- [FaultContract(typeof(Guid))]
- int DoSomething();
- }
Now my method can throw either FaultException<ErrorMessage> or FaultException<Guid>.
If a web service throws a FaultExeption<T> of a type not declared in the ServiceContract, it will not reach the client. For example, if the ServiceContract says I will throw a FaultException<ErrorMessage>, and my service instead throws a FaultException<string>, WCF will block my fault. Instead, it will send the client a bare FaultException with the generic message «The server was unable to process the request due to an internal error.»
Best Practices
There are no shortage of people offering their own advice about error handling. I have only a few points to make.
First and most important, you should be very cautious about providing detailed information to the client about what went wrong. Most error details are either a security risk or simply irrelevant to the client. For example, the Stack Trace contains details about your code which should not be revealed. Even if the client is another division within your own company, they don’t need you to send them the Stack Trace. If you sent them the Stack Trace, what would they do with it? Likewise, it’s not a good idea to simply catch exceptions and pass the exception Message to the client.
There are only a few types of messages that the client may care about. For example, if the client did not provide a required field, informing the client might be useful. If the system is down temporarily, you could tell the client to try later. Error messages that reveal details about your code, however, don’t help the client but do provide security risks.
Using an ErrorMessage class like the one shown above may be sufficient. The client is informed that something went wrong. It anyone needs more information, they can provide you with a ticket number, and you can look up the error in the error log.
One other suggestion: if you are going to provide any significant error information, it would be best to have a FaultContract. Even though the basic FaultException class allows you to pass a message and a FaultCode and a FaultReason (and a few other things not discussed in this article), it makes sense to forego these and use a FaultException<T>, with all your error information inside the detail object T. That way the client knows exactly what to expect and doesn’t try reading a value from the FaultReason when there’s no FaultReason provided.
In conclusion, WCF provides you with a lot of options for error handling. As long as you think carefully about what information you are providing and the format in which you provide it, you should come out fine.
Однако проблема заключается в перерегистрации ASP.Net в IIS, что объясняется ниже.
А также, если вы на 64-битной машине всегда используете пути Framework64: C:WindowsMicrosoft.NETFramework64v4.0.30319 > aspnet_regiis.exe -iru
Ниже приведено объяснение от Microsoft:
http://download.microsoft.com/download/0/A/E/0AEB3BC1-506E-4954-8AB1-4FA2EE75985C/ReleaseNotes.docx
При попытке запустить службу, которая принимает сообщения по HTTP-транспорту, вы можете получить ошибку, аналогичную следующей:
Ошибка сервера в приложении «/WCFApplication»
Не удалось загрузить тип ‘System.ServiceModel.Activation.HttpModule’ из сборки ‘System.ServiceModel, Version = 3.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089’.
Описание: Необработанное исключение возникло во время выполнения текущего веб-запроса. Просмотрите трассировку стека для получения дополнительной информации об ошибке и ее возникновении в коде.
Сведения об исключении: System.TypeLoadException: Не удалось загрузить тип ‘System.ServiceModel.Activation.HttpModule’ из сборки ‘System.ServiceModel, Version = 3.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089’.
Эта ошибка может возникнуть, когда IIS установлен после установки .NET Framework 4 или если версия 3.0 модуля активации HF для WCF установлена после установки IIS и .NET Framework 4.
Чтобы устранить эту проблему, вы должны использовать ASP.NET IIS Registration Tool (Aspnet_regiis.exe,) для регистрации правильной версии ASP.NET. Это можно сделать, используя параметры -iru при запуске aspnet_regiis.exe следующим образом:
aspnet_regiis.exe -iru
И кредит, где он должен: Источник